<template>
  <div class="shared-calendar-edit">
    <div class="header">
      <svg-icon name="back" class="back-btn" @click="back" />
    </div>

    <div class="shared-calendar-main">
      <van-form @submit="onSubmit">
        <van-cell-group class="!mb-[1.2rem]">
          <van-field
            v-model="planForm.visitDate"
            is-link
            readonly
            name="datePicker"
            label="出访日期"
            placeholder="点击选择时间"
            @click="showPicker = true"
          />
          <DateTime
            :values="planForm.visitDate"
            @changeValue="showPicker = false"
            :showPicker="showPicker"
            @confirm="onConfirm"
          />
        </van-cell-group>

        <van-cell-group class="!mb-[1.2rem]">
          <van-field
            label="出访公司"
            v-model="planForm.customName"
            placeholder="请输入出访公司"
          />
        </van-cell-group>

        <van-cell-group class="!mb-[1.2rem]">
          <van-field
            label="出访对象"
            v-model="planForm.visiteesName"
            placeholder="请输入出访对象"
          />
        </van-cell-group>

        <van-cell-group class="!mb-[1.2rem]">
          <van-field
            label="同行人员"
            placeholder="请选择同行人员"
            v-model="peersNames"
            @focus="addPeople"
            type="textarea"
            autosize
            readonly
          >
          </van-field>
        </van-cell-group>

        <div class="join-exit">
          <van-button
            size="small"
            type="danger"
            @click="exitBtn"
            v-if="planForm.isJoin === 'Y'"
          >
            退出
          </van-button>

          <van-button
            size="small"
            type="danger"
            @click="joinBtn"
            v-if="planForm.isJoin === 'N'"
          >
            加入
          </van-button>
        </div>

        <div class="submit-btn">
          <van-button
            block
            type="primary"
            native-type="submit"
            color="linear-gradient(to right, #ffadb3, #ff4350)"
          >
            发布
          </van-button>
        </div>
      </van-form>
    </div>

    <van-popup
      v-model:show="showPeople"
      round
      position="bottom"
    >
      <van-field
        v-model="keyWords"
        clearable
        label="用户名"
        placeholder="请输入用户名搜索"
      />

      <div class="people-box">
        <van-checkbox-group
          v-model="planForm.peersName"
          shape="square"
          class="people-checkbox"
        >
          <van-checkbox
            v-for="(item, index) of searchPeers"
            :key="index"
            :name="item.userId"
          >{{ item.nickName }}</van-checkbox
          >
        </van-checkbox-group>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts" name="ShareCalendarEdit">
import { useRoute, useRouter } from "vue-router";
import { computed, ref } from "vue";
import {
  exitPeers,
  getUserList,
  joiningPeers,
  planDetail,
  savePlan,
  updatePlan
} from "@/views/sharedCalendar/fetchData";
import {
  closeToast,
  showConfirmDialog,
  showLoadingToast,
  showSuccessToast,
  showToast
} from "vant";
import DateTime from "@/components/DateTime/index.vue";

const route = useRoute();
const router = useRouter();
const date = route.query.date as string;
const id = route.query.id as string;
const showPicker = ref(false);
const showPeople = ref(false);
const keyWords = ref("");

const initForm = () => {
  return {
    id: "",
    isJoin: "",
    visitDate: date,
    visitTime: "",
    visiteesName: "",
    peersName: [] as string[],
    visitorName: "",
    customName: "",
    addPeersIds: "",
    delPeersIds: "",
    peersNameList: []
  };
};
const planForm = ref(initForm());
const peersNameList = ref<string[]>([]);
const peersList = ref<Record<string, any>[]>([]);
const peersNames = computed(() => {
  const arr = [];
  peersList.value.forEach(item => {
    if (planForm.value.peersName.includes(item.userId)) arr.push(item.nickName);
  });
  return arr.join(",");
});
const searchPeers = computed(() => {
  if (!keyWords.value) return peersList.value;
  return peersList.value.filter(item => item.nickName.includes(keyWords.value));
});

function back() {
  router.back();
}

function onConfirm(selectedValues: string) {
  planForm.value.visitDate = selectedValues;
  showPicker.value = false;
}

function addPeople() {
  showPeople.value = true;
}

function joinBtn() {
  showConfirmDialog({
    title: "加入",
    message: "是否确认加入该拜访计划？"
  })
    .then(() => {
      joiningPeers({ id: planForm.value.id }).then((res: any) => {
        if (res.code === 200) showSuccessToast("加入成功");
        back();
      });
    })
    .catch(() => {});
}

function exitBtn() {
  showConfirmDialog({
    title: "退出",
    message: "是否确认退出该拜访计划？"
  })
    .then(() => {
      exitPeers({ id: planForm.value.id }).then((res: any) => {
        if (res.code === 200) showSuccessToast("退出成功");
        back();
      });
    })
    .catch(() => {});
}

function onSubmit() {
  planForm.value.addPeersIds = planForm.value.peersName.join(",");
  if (planForm.value.id) {
    const delIds: string[] = [];
    peersNameList.value.forEach(item => {
      if (!planForm.value.peersName.includes(item)) delIds.push(item);
    });
    planForm.value.delPeersIds = delIds.join(",");
    updatePlan(planForm.value).then((res: any) => {
      if (+res.code === 200) {
        showToast("修改成功");
        setTimeout(() => {
          back();
        }, 1000);
      }
    });
  } else {
    savePlan(planForm.value).then((res: any) => {
      if (+res.code === 200) {
        showToast("新增成功");
        setTimeout(() => {
          back();
        }, 1000);
      }
    });
  }
}

function getDetail() {
  if (!id) return;
  showLoadingToast({
    duration: 0, // 持续展示 toast
    forbidClick: true,
    overlay: true,
    message: "加载中..."
  });
  planDetail(id)
    .then((res: any) => {
      planForm.value = res.data;
      planForm.value.peersName = [];
      const arr = planForm.value.peersNameList || [];
      arr.forEach((item: Record<string, string>) => {
        planForm.value.peersName.push(...Object.keys(item));
      });
      peersNameList.value = JSON.parse(
        JSON.stringify(planForm.value.peersName)
      );
    })
    .finally(() => closeToast());
}

function getUsers() {
  getUserList().then((res: any) => {
    peersList.value = res || [];
  });
}

getDetail();
getUsers();
</script>

<style scoped lang="less">
.shared-calendar-edit {
  display: flex;
  flex-direction: column;

  .header {
    display: flex;
    align-items: center;
    height: 4rem;
    margin-bottom: 1rem;
    padding: 0 1rem;
    background-color: #fff;
    border-radius: 0 0 1rem 1rem;

    .back-btn {
      width: 2rem;
      height: 2rem;
    }
  }

  .shared-calendar-main {
    height: 0;
    flex: 1;
    padding: 0 1rem 1rem;
    overflow: auto;
  }

  .people-checkbox {
    padding: 1rem 1rem 0.5rem 2.2rem;

    .van-checkbox {
      margin-bottom: 1rem;
    }
  }

  .join-exit {
    display: flex;
    justify-content: flex-end;
    margin: 1rem;
  }

  .people-box {
    height: 46vh;
    overflow: auto;
  }
}
</style>
